from flask import current_app
from extensions import db
from task_app.extensions import scheduler

from task_app.models import JobPlan
from task_app.tasks import api_scheduler_handler

from task_app.utils import fix_job_def


def add_apscheduler(plan: JobPlan):
    # 添加apscheduler job
    job_def = {
        "trigger": plan.trigger_type
    }
    job_def.update(plan.trigger_kwargs)
    fix_job_def(job_def)
    current_app.logger.info("【添加scheduler_job】-->job_def:%s" % job_def)
    scheduler.add_job(
        id=plan.task_id,
        func=api_scheduler_handler,
        args=[plan],
        replace_existing=True,
        coalesce=True,
        **job_def
    )
    current_app.logger.info("【添加定时任务成功】-->task_id:%s" % plan.task_id)


def edit_apscheduler(plan: JobPlan):
    """ 更新 job 状态"""

    status = int(plan.status)
    task_id = str(plan.task_id)
    task = scheduler.get_job(task_id)
    if task:
        if status == 1:
            scheduler.resume_job(task_id)
            current_app.logger.info("【恢复scheduler_job】-->task_id:%s" % task_id)
        if status == 2 or status == 3:
            scheduler.pause_job(task_id)
            current_app.logger.info("【暂停scheduler_job】-->task_id:%s" % task_id)


def modify_apscheduler(plan: JobPlan):
    """ 更新 job 属性"""

    task_id = str(plan.task_id)
    task = scheduler.get_job(task_id)
    if task:
        job_def = {
            "trigger": plan.trigger_type
        }
        job_def.update(plan.trigger_kwargs)
        fix_job_def(job_def)
        current_app.logger.info("【准备更改scheduler_job属性】-->job_def:%s" % job_def)
        scheduler_job = scheduler.modify_job(id=task_id, **job_def)
        plan.next_run_time = scheduler_job.next_run_time
        db.session.commit()
        current_app.logger.info("【已更改scheduler_job属性成功】-->job_def:%s" % job_def)


def remove_apscheduler(plan: JobPlan):
    """ 删除job """
    if scheduler.get_job(plan.task_id):
        scheduler.remove_job(plan.task_id)
        current_app.logger.info("【删除scheduler_job】-->task_id:%s" % plan.task_id)
